package com.charging.controller.user;

import com.charging.entity.Announcement;
import com.charging.entity.ChargingPile;
import com.charging.entity.ChargingRecord;
import com.charging.entity.User;
import com.charging.service.AnnouncementService;
import com.charging.service.ChargingPileService;
import com.charging.service.RecordService;
import com.charging.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private AnnouncementService announcementService;
    @Autowired
    private ChargingPileService chargingPileService;
    @Autowired
    private RecordService recordService;

    @GetMapping("/login")
    public String showLoginForm() {


        return "user/login";
    }

    // 处理登录请求
    @PostMapping("/login")
    public ModelAndView login(
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session
    ){

        ModelAndView mv = new ModelAndView();


    // 2. 验证码正确，再校验用户
    User user = this.userService.getUserByUserNameAndPassword(username, password);
     if (user == null) {
        mv.addObject("errorMsg", "用户名或密码错误！");
        mv.setViewName("/user/login");
        return mv;
    }

        // 根据角色处理
        switch (user.getRole()) {
            case 0:
                session.setAttribute("user", user);
                mv.setViewName("/user/home"); // 普通用户主页
                break;
            case 1:
                session.setAttribute("admin", user);
                mv.setViewName("/admin/dashboard"); // 管理员仪表盘
                break;
            case 2:
                session.setAttribute("tester", user);
                mv.setViewName("/tester/dashboard"); // 测试员工作区
                break;
        }



     return mv;
}

    @GetMapping("/register")
    public String showRegisterForm() {
        return "user/register";
    }

    @PostMapping("/register")
    public String register(User user, RedirectAttributes redirectAttributes) {
        try {
            userService.register(user);
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "/user/login";
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            System.out.println("注册失败");
            return "/user/register";
        }
    }

    // 用户主页
    @GetMapping("/home")
    public String userDashboard( Model model, HttpSession session) {

        // 检查登录状态
        User user = (User) session.getAttribute("user");
        // 检查用户是否登录
        Long userid = user.getId();
        System.out.println("user"+user);
        if (userid == null) {
            return "redirect:/user/login";
        }

        model.addAttribute("user", user);

        // 获取所有有效公告
        List<Announcement> announcements = announcementService.getAllValidAnnouncements();
        model.addAttribute("announcementList", announcements);

        List<ChargingRecord> recordList = recordService.getAllRecords();
        model.addAttribute("recordList", recordList);

        List<ChargingPile> chargingPiles = chargingPileService.findAll();
        model.addAttribute("chargingPileList",chargingPiles);
        return "user/home";
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("currentUser");
        return "redirect:/user/login";
    }

    @PostMapping("/update-location")
    public ResponseEntity<?> updateLocation(
            @RequestParam Long userId,
            @RequestParam Double lat,
            @RequestParam Double lng) {
        userService.updateUserLocation(userId, lat, lng);
        return ResponseEntity.ok().build();
    }

}
